<template>
  <div class="app-container workReport">
    <el-row :gutter="10" class="mb6" justify="end">
      <el-col :span="24">
        <el-radio-group v-model="queryParams.reportSubmitType">
          <el-radio-button
            v-for="item in report_submit_type"
            :key="item.value"
            :label="item.value"
            @change="handleQuery"
            >{{ item.label }}</el-radio-button
          >
        </el-radio-group>
      </el-col>
    </el-row>

    <el-row :gutter="8" justify="space-between">
      <el-col :span="22.5" class="w-21/24">
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item prop="keyword" class="w-3/24">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入关键词"
              clearable
              class="w-full"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="reportDateArr" class="w-5/24">
            <el-date-picker
              class="w-full"
              v-model="queryParams.reportDateArr"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item prop="reportType" class="w-3/24">
            <el-select
              v-model="queryParams.reportType"
              placeholder="报告类型"
              clearable
              class="w-full"
            >
              <el-option
                v-for="dict in report_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="reviewStatus" class="w-3/24">
            <el-select
              v-model="queryParams.reviewStatus"
              placeholder="批阅状态"
              clearable
              class="w-full"
            >
              <el-option
                v-for="dict in review_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="_userIdArr" class="w-3/24">
            <el-select
              class="w-full"
              v-model="queryParams._userIdArr"
              :multiple="true"
              placeholder="选择提交人"
              @focus="selectUserFn('userIdArr')"
            >
              <el-option
                v-for="item in userOption['userIdArr']"
                :key="item.uuid"
                :label="item.label"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >新建报告</el-button
        >
      </el-col>
    </el-row>

    <div class="list">
      <div
        class="flex justify-between flex-row mb-6 p-7 border-solid border-1 border-slate-200"
        v-for="(item, index) in workReportList"
        :key="index"
      >
        <div class="basis-6/24 px-2">
          <div class="text-gray-400 pb-7">报告标题</div>
          <div class="text-xl">
            <span>{{ parseTime(item.reportStartDate, '{y}-{m}-{d}') }}</span>
            <span v-if="item.reportEndDate"
              >至{{ parseTime(item.reportEndDate, '{y}-{m}-{d}') }}</span
            >
            <span v-if="item.reportType">工作</span>
            <dict-drop
              style="display: inline-block"
              :options="report_type"
              :value="item.reportType"
            ></dict-drop>
          </div>
        </div>
        <div class="basis-2/24 px-2">
          <div class="text-gray-400 pb-7">提交人员</div>
          <div class="text-xl">{{ item.createName }}</div>
        </div>
        <div class="basis-2/24 px-2">
          <div class="text-gray-400 pb-7">报告类型</div>
          <div class="text-xl">
            <dict-drop
              :options="report_type"
              :value="item.reportType"
            ></dict-drop>
          </div>
        </div>
        <div class="basis-3/24 px-2">
          <div class="text-gray-400 pb-7">所属部门</div>
          <div class="text-xl">{{ item.deptName }}</div>
        </div>
        <div class="basis-3/24 px-2">
          <div class="text-gray-400 pb-7">批阅状态</div>
          <div class="text-xl">
            <dict-drop
              :options="review_status"
              :value="item.reviewStatus"
            ></dict-drop>
          </div>
        </div>
        <div class="basis-3/24 px-2">
          <div class="text-gray-400 pb-7">提交状态</div>
          <div class="text-xl">
            <dict-drop
              :options="sys_work_report_submit"
              :value="item.isSubmit"
            ></dict-drop>
          </div>
        </div>
        <div class="basis-3/24 px-2">
          <div class="text-gray-400 pb-7">提交时间</div>
          <div class="text-xl">{{ item.submitTime }}</div>
        </div>
        <div class="basis-2/24 flex items-center">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="详情"
            placement="top"
          >
            <el-button type="primary" circle @click="rowClick(item)">
              <span class="i-ph-caret-circle-right-bold w-5 h-5"></span>
              <!-- <el-icon></el-icon> -->
            </el-button>
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="编辑"
            placement="top"
          >
            <el-button
              type="primary"
              :disabled="item.createBy !== userStore.userInfo.userName"
              circle
              @click="handleUpdate(item)"
              ><el-icon><EditPen /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除"
            placement="top"
          >
            <el-button
              type="danger"
              :disabled="item.createBy !== userStore.userInfo.userName"
              circle
              @click="handleDelete(item)"
            >
              <el-icon><DeleteFilled /></el-icon
            ></el-button>
          </el-tooltip>
        </div>
      </div>
      <div
        v-if="workReportList.length == 0"
        style="
          font-size: 16px;
          font-weight: 600;
          margin-top: 100px;
          text-align: center;
        "
      >
        <p><img src="@/assets/images/icon/empty.png" /></p>
        <p>未匹配到相关工作报告</p>
      </div>
    </div>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    />
  </div>
</template>

<script setup name="WorkReport">
import { listWorkReport, delWorkReport } from '@/api/workReport/index'
import { useRouter } from 'vue-router'
import { getCurrentInstance, reactive, ref, toRefs } from 'vue'
import { getTreeNodeByParam, getPricipalId } from '@/utils/commo'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const commonStore = useCommonStore()
const {
  report_submit_type,
  report_type,
  review_status,
  sys_work_report_submit
} = proxy.useDict(
  'report_submit_type', // --  报告提交类型
  'report_type', // --  报告类型
  'review_status', // --  批阅状态
  'sys_work_report_submit' //是否已提交
)

const workReportList = ref([])
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)

const data = reactive({
  selectArr: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reportSubmitType: '0'
  },
  userOption: { userIdArr: [] }, //人员选择下拉
  dialogParam: {}
})

const { selectArr, queryParams, userOption, dialogParam } = toRefs(data)

/** 查询公告列表 */
function getList() {
  // 发布人员
  queryParams.value.userIdArr = getPricipalId(
    userOption.value['userIdArr'],
    queryParams.value._userIdArr
  )
  loading.value = true
  listWorkReport(queryParams.value).then(response => {
    workReportList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 新增按钮操作 */
function handleAdd() {
  goTo('/rsgl/other/workReportForm')
}
/**修改按钮操作 */
function handleUpdate(row) {
  console.log('row', row)
  goTo('/rsgl/other/workReportForm', { workReportId: row.id })
}
/**详情按钮操作 */
function rowClick(row) {
  goTo('/rsgl/other/workReportDetails', { workReportId: row.id })
}
/** 删除按钮操作 */
function handleDelete(row) {
  const workReportIds = row.id || ids.value
  let msgTile = ''
  if (row.reportEndDate && row.reportType !== '0') {
    msgTile = `${row.createName}${proxy.parseTime(
      row.reportStartDate,
      '{y}-{m}-{d}'
    )}至${proxy.parseTime(
      row.reportEndDate,
      '{y}-{m}-{d}'
    )}的工作${proxy.selectDictLabel(report_type.value, row.reportType)}`
  } else {
    msgTile = `${row.createName}${proxy.parseTime(
      row.reportStartDate,
      '{y}-{m}-{d}'
    )}的工作${proxy.selectDictLabel(report_type.value, row.reportType)}`
  }
  proxy.$modal
    .confirm(`是否删除${msgTile}？`)
    .then(function () {
      return delWorkReport(workReportIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
function goTo(url, data) {
  router.push({ path: url, query: data })
}

/**
 * 人员选择
 * @param keyName handleId:经办人  transactionId:业务员
 */
function selectUserFn(keyName) {
  switch (keyName) {
    case 'userIdArr':
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择发布人员'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = true
      dialogParam.value.checkStrictly = false
      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = [queryParams.value['_' + keyName]]
      dialogParam.value.dataType = 'person'
      break
  }
}

// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'userIdArr':
      userOption.value.userIdArr = val.selectData
      queryParams.value._userIdArr = val.defaultCheckedKeys
      break
  }
}

/**
 * 根据当前用户id转为uuid（id前加u）
 * @param val 输入用户的id
 * @param fieldName 需要赋值的字段
 * @param selectArr 用户的字典
 */
async function getDefaultUserInfo(val, fieldName, selectArr) {
  let userTree = await commonStore.getUseTreeData()
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  if (Array.isArray(id)) {
    queryParams.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(userTree, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      queryParams.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(userTree, id, 'id', [])
    userOption.value[selectArr] = obj
    queryParams.value[fieldName] = obj[0].uuid
  }
}

getList()
</script>
<style lang="scss">
.workReport .list > div:nth-child(even) {
  background-color: #f7f7f7;
}
</style>
